package com.cn.qtms.base.entity;

import com.cn.qtms.feign.AuthService;
import com.cn.qtms.util.IdWorker;
import org.springframework.beans.factory.annotation.Autowired;

import javax.persistence.PrePersist;
import javax.persistence.PreUpdate;
import java.util.Date;
import java.util.Map;

/**
 * @Name:AuditingEntityListener
 * @Description:
 * @Author: zhangyang
 * @Date: 2019-08-26 23:45
 **/
public class AuditingEntityListener {

    @Autowired
    private AuthService authService;

    @PrePersist
    public void preSave(BaseEntity entity) {
        String username = "system";
        try {
            Map<String, Object> map = authService.info();
            if (map != null) {
                username = map.get("username").toString();
            }
        } catch (Exception ex) {
            username = "admin";
        }
        entity.setId(new IdWorker().nextId());
        entity.setIsDelete(false);
        entity.setCreator(username);
        entity.setCreateDate(new Date());
        entity.setUpdater(username);
        entity.setUpdateDate(new Date());
    }

    @PreUpdate
    public void preUpdate(BaseEntity entity) {
        String username = "system";
        try {
            Map<String, Object> map = authService.info();
            if (map != null) {
                username = map.get("username").toString();
            }
        } catch (Exception ex) {
            username = "admin";
        }
        entity.setCreator(entity.getCreator());
        entity.setCreateDate(entity.getCreateDate());
        entity.setUpdater(username);
        entity.setUpdateDate(new Date());
    }
}